package com.module.pubpage.ui.choiceCity

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.adapter.choiceArea.InnerListener
import com.common.app.adapter.decoration.DividerItemDecoration
import com.common.app.adapter.decoration.SectionItemDecoration
import com.common.app.core.RouterHub
import com.common.app.data.bean.LocateState
import com.common.app.data.bean.BaseCityModel
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.Utils
import com.common.app.utls.Utils.getCountryList
import com.common.app.utls.Utils.getHotCountryList
import com.common.app.utls.report.ReportEventManager.findByCityModel
import com.common.app.widget.pinyinSortBar.SideIndexBar
import com.common.base.app.activity.BaseNavActivity
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ViewUtils
import com.module.pubpage.R
import com.module.pubpage.databinding.PubpageActivityChoiceRegionBinding
import java.util.*


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：7/2/2023
 *
 * 描述：选择国家或区号页
 *
 * 修订历史：
 *
 */
@Route(path = RouterHub.ROUTER_PUBPAGE_CHOICE_CITY)
class ChoiceCityActivity :
    BaseNavActivity<PubpageActivityChoiceRegionBinding>(),
    View.OnClickListener, SideIndexBar.OnIndexTouchedChangedListener,
    InnerListener {

    private var mAdapter: CityListAdapter? = null
    private var mAllCities: MutableList<BaseCityModel> = ArrayList()
    private var mHistoryCities: MutableList<BaseCityModel> = ArrayList()
    private var mHotCities: MutableList<BaseCityModel> = ArrayList()
    private var mResults: MutableList<BaseCityModel> = ArrayList()

    private var mLocatedCity: BaseCityModel? = null
    private var locateState = 0

//    override fun getViewModel(): Class<MeViewModel> = MeViewModel::class.java

    override fun getViewContentBinding() =
        PubpageActivityChoiceRegionBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle("选择国家或区号")

    }

    override fun initEvents() {
        mViewContentBinding.cpSideIndexBar.setOverlayTextView(mViewContentBinding.cpOverlay)
            .setOnIndexChangedListener(this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        //初始化热门城市
        if (mHotCities.isEmpty()) {
            mHotCities.addAll(getHotCountryList(this))
        }
        //初始化定位城市，默认为空时会自动回调定位
        if (mLocatedCity == null) {
            mLocatedCity = BaseCityModel(getString(R.string.common_cp_locating), "未知", "定位城市", "0")
            locateState = LocateState.LOCATING
        } else {
            locateState = LocateState.SUCCESS
        }
        mAllCities.addAll(getCountryList(this))

//        mAllCities.add(0, mLocatedCity);

        val plays: MutableList<BaseCityModel> = findByCityModel()
        if (plays.isNotEmpty()) {
            mHistoryCities.addAll(plays)
            mAllCities.add(0, BaseCityModel("历史搜索", "未知", "历史搜索", "-1"))
            mAllCities.add(1, BaseCityModel("热门城市", "未知", "热门城市", "0"))
        } else {
            mAllCities.add(0, BaseCityModel("热门城市", "未知", "热门城市", "0"))
        }
        mResults = mAllCities
        initCouView()
        requestCityList()
    }

    override fun onClick(v: View?) {
        //防止多次点击
        if (ViewUtils.isFastClick()) return
    }

    private fun initCouView() {
        mViewContentBinding.cpCityRecyclerview.setHasFixedSize(true)
        mViewContentBinding.cpCityRecyclerview.addItemDecoration(
            SectionItemDecoration(
                this,
                mAllCities
            ), 0
        )
        mViewContentBinding.cpCityRecyclerview.addItemDecoration(DividerItemDecoration(this), 1)
        mAdapter = CityListAdapter(this, mAllCities, mHotCities, mHistoryCities,false)
        mAdapter?.autoLocate(true)
        mAdapter?.setInnerListener(this)
        mAdapter?.setLayoutManager(mViewContentBinding.cpCityRecyclerview.getLinearLayoutManager())
        mViewContentBinding.cpCityRecyclerview.adapter = mAdapter
        mViewContentBinding.cpCityRecyclerview.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //确保定位城市能正常刷新
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mAdapter?.refreshLocationItem()
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {}
        })
    }

    override fun onIndexChanged(index: String?, position: Int) {
        //滚动RecyclerView到索引位置
        mAdapter?.scrollToSection(index)
    }

    override fun itemLocationClick(position: Int, data: BaseCityModel?) {
//        showToast(data?.name)
        val intent = Intent()
        intent.putExtra("mName", data?.name)
        intent.putExtra("mId", data?.code)
        setResult(RESULT_OK, intent)
        finish()
    }

    override fun locate() {

        val mHotCities: MutableList<BaseCityModel> = ArrayList()
        mAdapter?.updateHotData(mHotCities)
    }


    /**
     * 地区数据
     */
    private fun requestCityList() {
        mAllCities.clear()
        mAllCities.addAll(Utils.getCityList())
    }
}